# -*- coding: utf-8 -*-

import json
import logging
from logging import config
from server import netstream
from server.dispatcher import Dispatcher
from server.netstream import nethost
from server.loginservice import LoginService
from server.chatservice import ChatService
from server.chessservice import ChessService
from server.tickservice import TickService

config.fileConfig('logging.conf')


class ChessServer(object):

    def __init__(self):
        self.host = nethost(8)
        self.host.startup(2000)
        logging.info('service startup at port %s', self.host.port)
        self.host.settimer(2000)
        self.userList = {}
        # 初始化分发器并注册服务
        self.dispatch = Dispatcher()
        self.dispatch.register(LoginService.SERVICE_ID, LoginService())
        self.dispatch.register(ChatService.SERVICE_ID, ChatService())
        self.dispatch.register(ChessService.SERVICE_ID, ChessService("server/database/user.db"))
        self.dispatch.register(TickService.SERVICE_ID, TickService())

    def startup(self):
        shutdown = False
        while not shutdown:
            self.host.process()
            event, wparam, lparam, data = self.host.read()
            if event < 0: continue
            # 处理玩家数据
            if event == netstream.NET_DATA:
                data = json.loads(data)
                logging.debug(data)
                if data['sid'] == 101:
                    # 客户端退出时删除用户
                    del self.userList[data['user']]
                    self.host.send(wparam, json.dumps(data))
                elif data['sid'] == 103:
                    # 关联用户昵称和hid
                    data['result'] = 'USER_EXIST'
                    if data['user'] not in self.userList:
                        data['result'] = 'USER_OK'
                        self.userList[data['user']] = wparam
                    self.host.send(wparam, json.dumps(data))
                else:
                    result = self.dispatch.dispatch(data)
                    # 返回数据到发送者
                    if result['sendType'] == 1:
                        self.host.send(wparam, json.dumps(result))
                    # 群聊消息
                    elif result['sendType'] == 2:
                        for _, user in self.userList.iteritems():
                            self.host.send(user, json.dumps(result))
                    # 发给部分人
                    elif result['sendType'] == 3:
                        if "userlist" in result:
                            for user in result['userlist']:
                                self.host.send(self.userList[user], json.dumps(result))
                                self.host.process()
            # 处理玩家进入
            elif event == netstream.NET_NEW:
                data = {'sid': LoginService.SERVICE_ID, 'cid': 1001, 'addr': data}
                result = self.dispatch.dispatch(data)
                self.host.send(wparam, json.dumps(result))
                self.host.settag(wparam, wparam)
                self.host.nodelay(wparam, 1)
            # 处理玩家离开
            elif event == netstream.NET_LEAVE:
                data = {'sid': LoginService.SERVICE_ID, 'cid': 1002}
                self.dispatch.dispatch(data)
                self.host.close(wparam)
            # 处理定时器
            elif event == netstream.NET_TIMER:
                # 定时推送桌子列表
                data = {'sid': 100, 'cid': 1001}
                result = self.dispatch.dispatch(data)
                for _, user in self.userList.iteritems():
                    self.host.send(user, json.dumps(result))
                # 定时推送分数列表
                data = {'sid': 100, 'cid': 1008}
                result = self.dispatch.dispatch(data)
                for _, user in self.userList.iteritems():
                    self.host.send(user, json.dumps(result))

if __name__ == "__main__":
    chessserver = ChessServer()
    chessserver.startup()
